import pandas as pd
import os

input_path = r"D:\Download\Download230618\04-25\2024q4.csv"
output_dir = './res/2024q4'
suffix = '_2024q4'

# 1. 读取总表
df = pd.read_csv(input_path, encoding="gbk")

# 2. 小表列名定义（保持你的顺序）
table_columns = {
    "temp_lzy_xs_airport_tourist_attr02": ["p_day", "p_index", "p_index_desc", "p_dir", "user_flag", "cnt"],
    "temp_lzy_xs_airport_stay01": ["p_day", "user_flag", "avg_stay_time_h"],
    "temp_lzy_xs_airport_stay02": ["p_day", "user_flag", "stay_time_h", "cnt"],
    "temp_lzy_xs_airport_result01": ["trans_type", "ratio"],
    "temp_lzy_xs_airport_result02": ["o_flag", "d_flag", "avg_cnt_per_day"],
    "temp_lzy_xs_airport_result03": ["user_flag", "o_flag", "d_flag", "avg_cnt_per_day"],
    "temp_lzy_xs_airport_result04": ["p_dir", "user_flag", "o_city_name", "o_county_name", "d_city_name", "d_county_name", "cnt_day_avg", "ratio_day_avg"],
    "temp_lzy_xs_airport_result05": ["p_day", "time_window", "window_start_time", "num_passengers"],
    "temp_lzy_xs_airport_result06": ["p_day", "time_window", "window_start_time", "num_passengers"],
    "temp_lzy_xs_airport_security_flow_by_time": ["p_day", "time_window", "window_start_time", "num_passengers"],
    "temp_lzy_anjian_result01": ["p_day", "time_before_check", "num_passengers"],
    "temp_lzy_anjian_result02": ["p_day", "time_after_check", "num_passengers"],
    "temp_lzy_anjian_result03": ["p_day", "time_window", "window_start_time", "num_points"],
    "temp_lzy_xs_airport_security_flow_by_time_fix": ["p_day", "time_window", "window_start_time", "num_passengers"],
    "temp_lzy_anjian_result01_fix": ["p_day", "time_before_check", "num_passengers"],
    "temp_lzy_anjian_result02_fix": ["p_day", "time_after_check", "num_passengers"],
    "temp_lzy_chujing_destination": ["arrive_prov", "cnt_arrive"],
    "temp_lzy_chujing_airport": ["leave_city", "cnt_out"]
}

# 3. 建立映射（小表实际名字带季度后缀）
table_name_mapping = {}
for short_name, columns in table_columns.items():
    full_name = short_name + suffix
    table_name_mapping[full_name] = columns

# 4. 确保输出目录存在
os.makedirs(output_dir, exist_ok=True)

# 5. 拆分并处理每个小表（加编号保存）
for idx, (full_table_name, columns) in enumerate(table_name_mapping.items(), start=1):
    # 筛选属于当前小表的数据
    sub_df = df[df['table_name'] == full_table_name].copy()

    if sub_df.empty:
        print(f"表 {full_table_name} 没有数据，跳过。")
        continue

    # 把前8列映射为小表列名
    rename_dict = {f'list_{i + 1}': col for i, col in enumerate(columns)}
    used_list_cols = list(rename_dict.keys())
    sub_df = sub_df[used_list_cols]

    # 重命名
    sub_df.rename(columns=rename_dict, inplace=True)

    # 保存文件，前缀加上编号（两位数）
    output_filename = f"{idx:02d}_{full_table_name}.csv"
    output_path = os.path.join(output_dir, output_filename)

    sub_df.to_csv(output_path, index=False, encoding="gbk")
    print(f"已保存：{output_path}")
